import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { getAllMenusApi } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { usePreferencesStore } from '#/store';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };

  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      // message.loading({
      //   content: `${$t('common.loadingMenu')}...`,
      //   duration: 1.5,
      // });
      const preferencesStore = usePreferencesStore();
      await preferencesStore.getAppInfo();
      const menus = await getAllMenusApi(pageMap);
      const allMenus = [
        {
          // 这里固定写死 BasicLayout，不可更改
          component: 'BasicLayout',
          meta: {
            order: -1,
            title: 'page.dashboard.title',
          },
          name: 'Dashboard',
          path: '/',
          redirect: '/analytics',
          children: [
            {
              name: 'Analytics',
              path: '/analytics',
              // 这里为页面的路径，需要去掉 views/ 和 .vue
              component: '/dashboard/analytics/index',
              meta: {
                affixTab: true,
                title: 'page.dashboard.analytics',
              },
            },
            {
              name: 'Workspace',
              path: '/workspace',
              component: '/dashboard/workspace/index',
              meta: {
                title: 'page.dashboard.workspace',
              },
            },
          ],
        },
       
        ...menus,
      ];
      return allMenus;
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
